package demo1;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;

import java.util.List;

/**
 * --------神兽出没--------/
 * ┌─┐     ┌─┐
 * ┌─┘─┴─────┘─┴─┐
 * │      ─      │
 * │  ┬─┘   └─┬  │
 * │             │
 * │      ┴      │  Code is far away from bug with the animal protecting
 * └───┐      ┌──┘  神兽保佑,代码无bug
 * │      │
 * │      └──────┐
 * │             ├┐
 * │             ┌┘
 * └┐ ┐ ┌───┬─┐ ┌┘
 * │ ┤ ┤   │ ┤ ┤
 * └─┴─┘   └─┴─┘
 * --------感觉萌萌哒--------/
 * <p>
 * zk继承AbstractZooKeeper实现对zk的操作
 *
 * @author wuyoushan
 * @date 2018/5/3
 */
public class ZookeeperOperator extends AbstractZooKeeper {

    /**
     * 创建持久态的znode,不支持多层创建.比如在创建/parent/child的情况下,无/parent.无法通过
     *
     * @param path 路径
     * @param data 数据
     */
    void create(String path, byte[] data) throws KeeperException, InterruptedException {
        /**
         * 此处采用的是CreateMode是PERSISTENT  表示The znode will not be automatically deleted upon client's disconnect.
         * EPHEMERAL 表示The znode will be deleted upon the client's disconnect.
         */
        this.zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    /**
     * 获取节点信息
     *
     * @param path 路径
     */
    void getChild(String path) throws KeeperException, InterruptedException {
        try {
            List<String> list = this.zooKeeper.getChildren(path, false);
            if (list.isEmpty()) {
                System.out.println(path + "中没有节点");
            } else {
                System.out.println(path + "中存在节点");
                for (String child : list) {
                    System.out.println("节点为:" + child);
                }
            }
        } catch (KeeperException.NoNodeException e) {
            throw e;
        }
    }

    /**
     * 判断节点是否存在，null为不存在
     *
     * @param node 节点
     */
    Stat existsNode(String node) throws KeeperException, InterruptedException {
        return this.zooKeeper.exists(node, false);
    }

    /**
     * 获取数据
     *
     * @param path 路径
     */
    byte[] getData(String path) throws KeeperException, InterruptedException {
        return this.zooKeeper.getData(path, false, null);
    }
}
